package com.ghsc.ghxc.jsb.ui.message.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.FragmentRobRedBinding
import com.ghsc.ghxc.jsb.ui.live.activity.RedExtensionIndexActivity
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusRedAttachment
import com.ghsc.ghxc.jsb.ui.message.view.CustMsgType
import com.ghsc.ghxc.jsb.ui.message.view.FrameAnimation
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum
import com.netease.yunxin.kit.chatkit.ui.model.ChatMessageBean

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.fragment
 * 类名：NewRobRedFragment
 * 创建时间：2024/6/4 14:46
 * 创建人 @author： xiaolin
 * 描述 ：Todo...抢红包
 */
class NewRobRedFragment : BaseVMFragment<NewRobRedFragmentViewModel, FragmentRobRedBinding>(R.layout.fragment_rob_red){

    private var bean : ChatMessageBean?=null
    private var beanRed : CusRedAttachment?=null

    companion object{
        fun newInstance(bean : ChatMessageBean): NewRobRedFragment {
            val fragment = NewRobRedFragment()
            fragment.bean = bean
            return fragment
        }
    }

    override fun attachVMClass(): Class<NewRobRedFragmentViewModel>? {
        return NewRobRedFragmentViewModel::class.java
    }

    override fun lazyLoad() {

    }
    private var mFrameAnimation: FrameAnimation? = null


    private val mImgResIds = intArrayOf(
        R.mipmap.icon_open_red_packet1,
        R.mipmap.icon_open_red_packet2,
        R.mipmap.icon_open_red_packet3,
        R.mipmap.icon_open_red_packet4,
        R.mipmap.icon_open_red_packet5,
        R.mipmap.icon_open_red_packet6,
        R.mipmap.icon_open_red_packet7,
        R.mipmap.icon_open_red_packet7,
        R.mipmap.icon_open_red_packet8,
        R.mipmap.icon_open_red_packet9,
        R.mipmap.icon_open_red_packet4,
        R.mipmap.icon_open_red_packet10,
        R.mipmap.icon_open_red_packet11
    )
    val userId: String by Preference(HttpConstant.USER_ID, "")

    override fun initView(savedInstanceState: Bundle?) {

        bean?.let {
            beanRed = it.messageData.message.attachment as CusRedAttachment
            GlideUtil.ImageHeadLoad(requireActivity(),beanRed!!.headimg,binding.imgUserHead)
            binding.tvUserName.text=beanRed!!.nickname
            binding.tvContent.text=beanRed!!.memo
            binding.tvDetails.visibility= View.GONE
            binding.imgOpen.visibility= View.VISIBLE
        }


    }

    override fun initClickListener() {
        super.initClickListener()
        binding.tvDetails.setSingleClickListener {
            //查看红包详情
            getStartActivity(1,"")
        }
        binding.llBtnClose.setSingleClickListener {
            stopAnim()
            //关闭弹窗
            dismiss?.invoke()
        }

        binding.imgOpen.setSingleClickListener {
            //领取红包
            if (mFrameAnimation != null) {
//                //如果正在转动，则直接返回
                return@setSingleClickListener
            }
            startAnim()
            val map: HashMap<String, Any> = HashMap()
            map["packet_id"] =beanRed!!.id.toString()
            val json=  GsonUtil.mapToJsonStrObjEncryption(map)
            mViewModel.onGetPacketSubmitMethod(json!!)
        }
    }
    private  fun startAnim(){
        mFrameAnimation = FrameAnimation(binding.imgOpen, mImgResIds, 125, true)
        mFrameAnimation!!.setAnimationListener(object : FrameAnimation.AnimationListener{
            override fun onAnimationStart() {
                loge("onAnimationStart")
            }

            override fun onAnimationEnd() {
                loge("onAnimationEnd")
            }

            override fun onAnimationRepeat() {
                loge("onAnimationRepeat")
            }

            override fun onAnimationPause() {
                binding.imgOpen.setBackgroundResource(R.mipmap.icon_open_red_packet1)
            }

        })
    }

    private  fun stopAnim() {
        if (mFrameAnimation != null) {
            mFrameAnimation!!.release()
            mFrameAnimation = null
        }
    }



    private  fun  getStartActivity(ifget :Int,message:String){
        if (ifget==1){
            var bundle = Bundle()
            bundle.putString("packetid",beanRed!!.id.toString())
            startActivity(RedExtensionIndexActivity().javaClass,bundle)
            //关闭弹窗
            dismiss?.invoke()
        }else {
            binding. tvContent.text= if(!TextUtils.isEmpty(message)) message else  "手慢了,红包已抢完"
            binding.tvDetails.visibility= View.VISIBLE
            stopAnim()
            binding.imgOpen.visibility= View.GONE

        }
    }

    //弹框关闭回调
    private var dismiss:(() -> Unit)? = null

    fun setOnDismissListener(listener: (() -> Unit)){
        this.dismiss = listener
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@NewRobRedFragment) {
                dismissLoading()
                showToast(it)
                //关闭弹窗
                dismiss?.invoke()
            }
            againLoginMsg.observe(this@NewRobRedFragment) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }

            getRewardErrorData.observe(this@NewRobRedFragment) {
                if (it.code == 3){
                    upMsg(3,it.msg)
                }else{
                    //其他错误
                    dismissLoading()
                    showToast(it.msg)
                    //关闭弹窗
                    dismiss?.invoke()
                }
            }

            onGetPacketSubmitData.observe(this@NewRobRedFragment){
                upMsg(1,it.msg)
            }
        }
    }
    private fun upMsg(sigg:Int,message:String){
        var expansion: HashMap<String, String> = hashMapOf()
        expansion[userId] = "1"
        if (bean!!.messageData.message.direct== MsgDirectionEnum.Out){
            expansion[bean!!.messageData.message.sessionId] = "1"
        }
        bean!!.messageData.message.localExtension= expansion as Map<String, Any>?
//        saveLocalMessageExt(bean!!.messageData.message, bean!!.messageData.message.time,true)
        NIMClient.getService(MsgService::class.java).updateIMMessage(bean!!.messageData.message) // 更新消息对象
        RxBus.getDefault().post(
            RxBusBean(
                CustMsgType.CUST_RED_RESU,
                CustMsgType.CUST_RED_RESU,bean!!.messageData.message
            )
        )
        getStartActivity(sigg,message)

    }
}
